//
//  ZQComposeViewController.m
//  柳州微博
//
//  Created by Apple_Lzzy45 on 16/11/3.
//  Copyright © 2016年 Apple_Lzzy40. All rights reserved.
//

#import "ZQComposeViewController.h"
#import "ZQAccountTool.h"
#import "ZQAccount.h"
#import "ZQTextView.h"
#import "ZQComposeToolbar.h"
#import "ZQComposePhotosView.h"
#import "ZQEmotion.h"
@interface ZQComposeViewController ()<UITextViewDelegate,ZQComposeToolbarDelegate ,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
/*输入*/
@property(nonatomic,strong)ZQTextView *textView;
/*工具条*/
@property(nonatomic,strong)ZQComposeToolbar *toolbar;
/*工具条*/
@property(nonatomic,strong)ZQComposePhotosView *photosView;
@end

@implementation ZQComposeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置导航栏
    [self setupNavi];
    
    //添加输入按钮
    [self setupTextView];
    //添加工具条
    [self setupToolbar];
    
    //添加照片
    [self setupPhotosView];
//    self.navigationItem.rightBarButtonItem.enabled=NO;
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //如果把下面这一句写在ViewDidLoad中 ，disabled的item颜色没有效果
    //有文本
    if (self.textView.text.length != 0 ) {
        //发送按钮可用
        self.navigationItem.rightBarButtonItem.enabled = YES;
        
    } else {//没有文本
        //发送按钮不可用
        self.navigationItem.rightBarButtonItem.enabled = NO;
        
    }
    
}

//控件销毁时执行
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    //隐藏键盘
    [self.textView resignFirstResponder];

}

/*自定义的方法*/

/**
 *  //添加照片
 */
-(void)setupPhotosView
{
    ZQComposePhotosView *photosView =[[ZQComposePhotosView alloc]init];
    photosView.y =90;
    photosView.width =self.view.width;
    photosView.height =300;
    
    //photosView.backgroundColor =[UIColor blueColor];
    [self.textView addSubview:photosView];
    //把局部变量赋值给全局或属性变量
    self.photosView =photosView;
}

//添加输入控件
-(void)setupTextView
{

    ZQTextView *textView =[[ZQTextView alloc]init];
       textView.size = self.view.bounds.size;
   // textView.
    textView.placeholder=@"随时随地分享新鲜事";
    
    //设置弹簧效果
    textView.alwaysBounceVertical =YES;
    
    textView.backgroundColor =[UIColor whiteColor];
    
    self.textView =textView;
    [self.view addSubview:textView];
    //h获得焦点
   // [self.textView  becomeFirstResponder];
    
    self.textView.delegate = self;

    //注册 监听文本事件
//  [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textChange) name:UITextViewTextDidChangeNotification object:textView];
   //注册 监听键盘frame改变事件
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(KeyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
//    
}
/**
 *  监听键盘frame改变事件
 *
 */
-(void)KeyboardWillChangeFrame:(NSNotification *)notification
{

    NSLog(@"监听键盘frame改变事件%@",notification);
    
    NSDictionary *userInfo =notification.userInfo;
    //键盘frame
    CGRect FrameBeg=[userInfo [UIKeyboardFrameBeginUserInfoKey]CGRectValue];
    
    CGRect FrameEnd=[userInfo [UIKeyboardFrameEndUserInfoKey]CGRectValue];

    //动画持续时间
    double duration =[userInfo [UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    //执行动画
    [UIView animateWithDuration:duration animations:^{
        //设置工具条的y =键盘的y  -工具条高度
        self.toolbar.y =FrameEnd.origin.y  -  self.toolbar.height;
    }];
}
////监听文本改变事件
//-(void)textChange
//{
//    self.navigationItem.rightBarButtonItem.enabled =self.textView.hasText;
//}
//添加工具条
-(void)setupToolbar
{
    ZQComposeToolbar *toolbar =[[ZQComposeToolbar alloc]init];
    toolbar.width =self.view.width;
    toolbar.height =44;
    
    toolbar.y=self.view.height -toolbar.height;
    [self.view addSubview:toolbar];
    self.toolbar=toolbar;
    //指定代理
    self.toolbar.delegate=self;
    //inputView设置键盘输入法
    //self.textView.inputAccessoryView =toolbar;
    
}
//实现代理
-(void)composeToobar:(ZQComposeToolbar *)toolbar didClickBtn :(ZQComposeToolbarButtonType) type
{
    switch (type) {
        case ZQComposeToolbarButtonTypePicture:
            NSLog(@"相册");
            //打开相册
            [self openAlbum];
            break;
           
        case ZQComposeToolbarButtonTypeMention:
            NSLog(@"@");
            break;
        case ZQComposeToolbarButtonTypeTrend:
            NSLog(@"#");
            break;
        case ZQComposeToolbarButtonTypeEmontion:
            NSLog(@"表情");
            
            [self opeEmotion];
            break;
        case ZQComposeToolbarButtonTypeCamera:
            NSLog(@"拍照");
            //打开相机
             [self openCamera];
            break;
        default:
            break;
    }

}

-(void)opeEmotion
{
    
    if (self.textView.inputView == nil) {
        
        ZQEmotion *viewEmotion = [[ZQEmotion alloc]init];
        
        viewEmotion.width = self.view.width;
        viewEmotion.height= 256;
        self.textView.inputView = viewEmotion;

    } else {
        self.textView.inputView = nil;
    }
    [self.textView resignFirstResponder];
    [self.textView becomeFirstResponder];
}
/**
 *  /打开相册
 */
-(void)openAlbum
{
    //打开相片库
    [self openImagePickerController:UIImagePickerControllerSourceTypePhotoLibrary];
}
//打开相机
-(void)openCamera
{
    //打开相片库
    [self openImagePickerController:UIImagePickerControllerSourceTypePhotoLibrary];
}
/**
 *  打开相片库
**/
-(void)openImagePickerController:(UIImagePickerControllerSourceType)type
{
    //判断资源是否可用,不可用 return
    if ([UIImagePickerController  isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]==NO) {
        return;
    }
    
    //图片选择控制器
    UIImagePickerController *ipc =[[UIImagePickerController alloc]init];
    
    //图片资源类型 :图库
    ipc.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
    
    //指定代理
    ipc.delegate =self;
    
    [self presentViewController:ipc animated:YES completion:nil];
    
}


/*
 *  获取图片资源的代理方法
 */
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSLog(@"%@",info);
    [picker dismissViewControllerAnimated:YES completion:nil];
    //info包含了选中图片
    UIImage *image =info[UIImagePickerControllerOriginalImage];
    //把图片添加到相册
    [self.photosView addPhoto:image];
    
}
//设置导航栏
-(void)setupNavi
{    //设置导航栏
    self.view.backgroundColor =[UIColor blueColor];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancel)];
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]initWithTitle:@"发送" style:UIBarButtonItemStyleDone target:self action:@selector(send)];
    self.navigationItem.rightBarButtonItem.enabled =NO;
    //获取用户名称
    NSString * name =[ZQAccountTool account].name;
    NSLog(@"%@",name);
    //
    NSString *prefix = @"发微博";
    UILabel *titleView =[[UILabel alloc]init];
    
    NSString *title =[NSString stringWithFormat:@"%@\n%@",prefix,name];
    titleView.width =200;
    titleView.height =44;
    titleView.numberOfLines = 0;
    titleView.textAlignment = NSTextAlignmentCenter;
    //  titleView.backgroundColor=[UIColor redColor];
    
    //创建带有属性的字符串
    NSMutableAttributedString *attributeTitle =[[NSMutableAttributedString alloc]initWithString:title];
    
    //获取 prefix字串Range
    NSRange prefixRange =[title rangeOfString:prefix];
    // NSLog(@"",prefixRange.location,)
    [attributeTitle addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:prefixRange];
    //添加属性
    //    NSRange range;
    //    range.length = 3;
    //    range.location =0;
    NSRange nameRange =[title rangeOfString:name];
    [attributeTitle addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:nameRange];
    //[attributeTitle addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:nameRange];
    titleView.attributedText =attributeTitle;
    
    self.navigationItem.titleView=titleView;
    

}

//取消
-(void)cancel
{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    [self.textView resignFirstResponder];
}
/**
*  发送微博 
*/
-(void)send
{
    NSLog(@"send--%@",self.textView.text);
    if (self.photosView.photos.count) {
        [self daiTu:self.textView.text];
    }else
    {
          [self faSong:self.textView.text];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//文本视图改变了
- (void)textViewDidChangeSelection:(UITextView *)textView
{
    //没有文本
    if (textView.text.length != 0 ) {
        //发送按钮可用
        self.navigationItem.rightBarButtonItem.enabled = YES;
        
    } else {//没有文本
        //发送按钮不可用
        self.navigationItem.rightBarButtonItem.enabled = NO;
        
    }
}
/**
*  发送微博 不带图
*/
-(void)faSong:(NSString *)text
{
    NSString *url = @"https://api.weibo.com/2/statuses/update.json" ;
    ZQAccount *acc = [ZQAccountTool account];
    //2.设置参数
    NSMutableDictionary * params=[NSMutableDictionary dictionary];
    
    params[@"access_token"]=acc.access_token;
    
    
    params[@"status"]=text;
    
    AFHTTPRequestOperationManager *Manager = [AFHTTPRequestOperationManager manager];
    
    [Manager POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        [MBProgressHUD showSuccess:@"发送成功！"];
        [self dismissViewControllerAnimated:YES completion:nil];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD showError:@"发送失败!"];
        NSLog(@"失败");
    }];
    

}
/**
 *  发送微博 带图
 */
-(void)daiTu : (NSString *)text
{
    NSString *url = @"https://upload.api.weibo.com/2/statuses/upload.json" ;
    ZQAccount *acc = [ZQAccountTool account];
    //2.设置参数
    NSMutableDictionary * params=[NSMutableDictionary dictionary];
    
    params[@"access_token"]=acc.access_token;
    
    params[@"status"]=text;
    
    UIImage *zq = [self.photosView.photos firstObject];
    
    NSData *data = UIImageJPEGRepresentation(zq, 1.0);
    
    AFHTTPRequestOperationManager *Manager = [AFHTTPRequestOperationManager manager];
    
    [Manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        
        [formData appendPartWithFileData:data name:@"pic" fileName:@"zq.jpg" mimeType:@"iamge/jpeg"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [MBProgressHUD showSuccess:@"发送成功！"];
        [self dismissViewControllerAnimated:YES completion:nil];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD showError:@"发送失败!"];
        NSLog(@"失败");
        
    }];
    
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
